//
//  UIImage.swift
//  RNAsmanMaster
//
//  Created by 李旭峰 on 8/13/19.
//  Copyright © 2019 Facebook. All rights reserved.
//

import Foundation
import AVFoundation
import MobileCoreServices
import Photos
import FCUUID
import SDWebImage

@objc extension UIImage {
  @objc func saveImageToAlbum(didCompleted:@escaping (_ imagePath:String?,_ error:Error?)->()){
    let tempImage:UIImage = self
    var localID: String!
    PHPhotoLibrary.shared().performChanges({
      let result = PHAssetChangeRequest.creationRequestForAsset(from: tempImage)
      let assetPlactholder = result.placeholderForCreatedAsset
      localID = assetPlactholder?.localIdentifier
    }) { (isSuccess, error) in
      if isSuccess {
        print("保存成功")
        //通过标识符获取对应的资源
        let assetResult = PHAsset.fetchAssets(withLocalIdentifiers: [localID], options: nil)
        let asset = assetResult[0]
        let options = PHContentEditingInputRequestOptions()
        options.canHandleAdjustmentData = {(adjustmeta: PHAdjustmentData) -> Bool in
          return true
        }
        //获取保存的图片路径
        asset.requestContentEditingInput(with: options, completionHandler: { (contentEditingInput: PHContentEditingInput?, info: [AnyHashable : Any]) in
          let file = contentEditingInput!.fullSizeImageURL!.absoluteString
          didCompleted(file,nil)
        })
      } else {
        didCompleted(nil,error)
        print("保存失败-->\(error!.localizedDescription)")
      }
    }
  }
  @objc func saveImage(didCompleted:@escaping (_ imagePath:String?,_ error:Error?)->()){
    let tempImage:UIImage = self
    
    guard let imageData = tempImage.jpegData(compressionQuality: 1.0) else {
      let error = NSError(domain: "asman", code: -10000, userInfo: ["message":"图片不存在"])
      didCompleted(nil,error)
      return
    }
    let imageName = FCUUID.uuid()!
    let tempPath = NSTemporaryDirectory().appending("\(String(describing: imageName)).jpeg")
    do {
      try imageData.write(to: URL(fileURLWithPath: tempPath))
      print("file path : \(tempPath)")
      didCompleted(tempPath,nil)
    }catch let err {
      didCompleted(nil,err)
    }
  }
  @objc static func image(withFilePath filePath:String,didCompleted:@escaping (_ image:UIImage?,_ error:Error?)->()){
    DispatchQueue.global().async {
      let videoUrl = URL(fileURLWithPath: filePath)
      let avAsset = AVAsset(url: videoUrl)
      let generator = AVAssetImageGenerator(asset: avAsset)
      generator.appliesPreferredTrackTransform = true
      let time = CMTimeMakeWithSeconds(0.0, preferredTimescale: 600)
      var actualTime:CMTime = CMTime(value: 0, timescale: 0)
      do {
        let imageRef = try generator.copyCGImage(at: time, actualTime: &actualTime)
        let image = UIImage(cgImage: imageRef)
        DispatchQueue.main.async {
          didCompleted(image,nil)
        }
      }catch let err {
        DispatchQueue.main.async {
          didCompleted(nil,err)
        }
      }
    }
  }
  @objc static func image(withUrlPath urlPath:String,didCompleted:@escaping (_ image:UIImage?,_ error:Error?)->()){
      guard let videoUrl = URL(string: urlPath) else {
          let userInfo = ["message":"视频路径异常"]
          let tempError = NSError(domain: "asman", code: -10000, userInfo: userInfo)
          didCompleted(nil,tempError)
          return
      }
      UIImage.download(url: videoUrl, completed: didCompleted)
  }
  
  @objc static func download(_ imagePath:String,completed:@escaping (_ image:UIImage?,_ error:Error?)->()){
        guard let imageUrl = URL(string: imagePath) else {
            let userInfo = ["message":"视频路径异常"]
            let tempError = NSError(domain: "asman", code: -10000, userInfo: userInfo)
            completed(nil,tempError)
            return
        }
        UIImage.download(url: imageUrl, completed: completed)
    }
  @objc static func download(url:URL,completed:@escaping (_ image:UIImage?,_ error:Error?)->()){
        DispatchQueue.global().async {
            SDWebImageManager.shared.loadImage(with: url, options: [], progress: nil) { (image, data, error, cacheType, success, url) in
                if let loadImage = image {
                    DispatchQueue.main.async {
                        completed(loadImage,error)
                    }
                }else{
                    DispatchQueue.main.async {
                        completed(image,error)
                    }
                }
            }
        }
    }
    
    /**
     resize and crop image
     
     - parameter toSize: destnation size
     
     - returns: destination image
     */
    func resizeAndCropImage(toSize: CGSize)-> UIImage{
        
        let widthFactor = toSize.width / self.size.width
        let heightFactor =  toSize.height / self.size.height
        
        var positionX:CGFloat = 0
        var positionY:CGFloat = 0
        let scaleFactor = widthFactor > heightFactor ? widthFactor : heightFactor
    
        let scaleWidth = scaleFactor * self.size.width
        let scaleHeight = scaleFactor * self.size.height
        
        if widthFactor > heightFactor {
            positionY = (toSize.height - scaleHeight) * 0.5
        } else {
            positionX = (toSize.width - scaleWidth) * 0.5
        }
        
        UIGraphicsBeginImageContext(toSize)
        self.draw(in: CGRect(x: positionX, y: positionY, width: scaleWidth, height: scaleHeight))
        
        return UIGraphicsGetImageFromCurrentImageContext()!
        
    }
}
